import sys

sys.path.append('..')  # 引入
from flask import Blueprint, render_template, request, jsonify
from flask_cors import CORS
import json
import os
from .modulse import *
from text_pack import qiantao
from io import BytesIO
import paddle
from pprint import pprint
from paddlenlp import Taskflow
from paddleocr import PaddleOCR, draw_ocr
import cv2
import pdfplumber
import numpy as np
from pymongo import MongoClient
import re
import datetime
from bson import BSON
from config.config_db import Config

blue = Blueprint('user', __name__)
CORS(blue)


# 蓝图用于路径管理和视图函数管理

@blue.route('/')
def index():
    return 'index'


@blue.route('/add/')
def add_name():
    u = User()
    # 创建对象
    u.name = 'hrp'
    # 以对象属性的方式创建数据
    db.session.add(u)
    # 将数据提交给缓存
    db.session.commit()
    # 将数据同步给数据库
    return 'success!'


@blue.route('/login/', methods=['GET', 'POST'])
def login():
    status = ""
    name = ""
    # 从post请求获取数据
    val = request.get_json()
    m3 = val.get("username")
    m4 = val.get("password")
    # print(m3)
    # print(m4)
    u2 = User.query.filter(User.user_er == m3).first()
    # print(u2)
    if u2 is None:
        status = "empty"
    else:
        # print(u2.password_er)
        if u2.password_er == m4:
            name = m3
            status = "success"
        else:
            status = "error"
        #    print(status)
    data = {
        "sta": status,
        "username": name
    }
    return data


# 用户存入数据库
@blue.route('/resign/', methods=['GET', 'POST'])
def resign():
    request_code = "error"
    val = request.get_json()
    m1 = val.get("username")
    m2 = val.get("password")
    if m1 is not None and m2 is not None:
        request_code = "success"
    # print(request.method)
    # print(m1)
    # print(m2)
    ur = User()
    ur.user_er = m1
    ur.password_er = m2
    db.session.add(ur)
    db.session.commit()
    print('success resign')
    return request_code


@blue.route('/test/', methods=['GET', 'POST'])
def test():
    resquest_code = 'error'
    # print(request)
    username = request.args.get("username")
    password = request.form.get('password')
    val = request.get_json()
    # print(val.get("username"))
    # print(val.get("password"))
    # print(val)
    # print(val.get("username") is not None&val.get("password") is not None)
    if val.get("username") is not None and val.get("password") is not None:
        resquest_code = 'success1'
    # print(username)
    # print(password)
    return resquest_code


@blue.route('/upload', methods=['POST'])
def upload():
    file = request.files['uploadFile']  # 接口字段

    user_name = request.form.get('user_name')  # 返回用户名字段
    print(user_name)

    filename, ext = os.path.splitext(file.filename)
    flag = False
    text = ""
    print(ext.lower())
    if ext.lower() == '.docx':
        file_data = BytesIO(file.read())
        text = qiantao.process_docx(file_data)  # 将docx文档中的文本进行获取
        flag = True
    elif ext.lower() == '.pdf':
        with pdfplumber.open(file) as pdf:
            for page in pdf.pages:
                text += page.extract_text()  # 提取pdf文本
        flag = True

    elif ext.lower() == '.jpg' or '.png':
        ocr = PaddleOCR(use_angle_cls=True, lang="ch")
        file_data = file.read()
        img = cv2.imdecode(np.fromstring(file_data, np.uint8), cv2.IMREAD_COLOR)  # 用cv2解码图像
        result = ocr.ocr(img, cls=True)
        for idx in range(len(result)):
            res = result[idx][1][0]  #
            text += res
        flag = True

    if flag == True:  #
        schema = ['姓名', '性别', '生日', '期望月薪', '期望从事行业', '期望工作地区', '毕业院校', '最高学历',
                  '工作经验年限']
        ids = Taskflow('information_extraction', schema=schema)
        data = ids(text)
        processed_data = {}  # 新建空字典用于存json
        for item in data:  # 遍历json的所有对象
            processed_item = {}  # 新建一个字典存单个对象
            for key, values in item.items():  # 遍历json对象的键值

                if key == '期望从事行业':
                    values = [x['text'] for x in item['期望从事行业']]  # 列表推导式，遍历整个key值为'期望从事行业'的值列表，将值列表中的text键的值组成新列表
                    processed_item[key] = values  # 将列表值和key组成新键值对
                    processed_data.update(processed_item)  # 将处理后的对象加入字典
                else:
                    max_prob_value = max(values, key=lambda x: x['probability'])  # 找到近似度属性值最大的值列表中的元素
                    processed_item[key] = max_prob_value['text']  # 将该元素中的text键值对作为值与键组成新的键值对
            processed_data.update(processed_item)  # 将处理后的对象加入字典
        json_data = json.dumps(processed_data)
        new_data = reset_data(processed_data, filename, user_name)
        print(new_data)
        db_insert(new_data)  # 写入数据库
        return jsonify(json.loads(json_data))
    else:
        return '分析失败'


def reset_data(data, file_name, username):
    salary_range = data['期望月薪'].split('-')
    min_salary = int(salary_range[0].strip('元/月'))
    max_salary = int(salary_range[1].strip('元/月'))
    time = datetime.datetime.now()
    date_str = time.strftime('%Y-%m-%d-%H:%M:%S')
    # 构造新的数据
    new_data = {
        '姓名': data['姓名'],
        '性别': data['性别'],
        '生日': data['生日'],
        '期望从事行业': data['期望从事行业'],
        '期望工作地区': data['期望工作地区'],
        '毕业院校': data['毕业院校'],
        '最高学历': data['最高学历'],
        '最低月薪': min_salary,
        '最高月薪': max_salary,
        '工作经验年限': int(data['工作经验年限'].replace("年", "")),
        '文件名': file_name,
        '用户': username,
        '上传时间': date_str 
    }
    print(new_data)
    return new_data


def db_insert(data):    
    # 连接 MongoDB
    client = MongoClient(Config.MONGO_URL)
    # 选择数据库和集合
    db = client[Config.MONGO_DB]
    collection = db[Config.MONGO_COL]
    try:
        collection.insert_many([data])  # 插入时要以列表形式插入，即使只有一个值
    except Exception as e:
        try:
            filter_query = {"文件名":data["文件名"]}#查询重复文件名
            update_query = {'$set': {'上传时间': data['上传时间'],'用户':data['用户']}}#更新上传时间和用户
            collection.find_one_and_update(filter_query,update_query)
        except  Exception as e2:
            print(e)
    # 关闭连接
    client.close()


@blue.route('/parse', methods=['POST'])
def parse():
    data = request.get_json()
    # data:{'workmax':'130k'，'workmin':'120k'，'workname’:"计算机'，'workschool':'研究生’,'workyear':'12’，'address':'江苏南通’}
    client = MongoClient(Config.MONGO_URL)
    # 选择数据库
    db = client[Config.MONGO_DB]
    # 选择集合（即表）
    collection = db[Config.MONGO_COL]
    # 构造查询条件
    query = {
        '最高月薪': {'$lte': int(data['workmax'])},  # gte大于等于，lte小于等于
        '最低月薪': {'$lte': int(data['workmin'])},
        '期望工作地区': data["address"],
        '最高学历': data['workschool'],
        '期望从事行业': {'$elemMatch': {'$regex': data['workname']}},
        '工作经验年限': {'$gte': int(data['workyear'])},
    }
    print(query)
    # 执行查询
    result = collection.find(query)
    json_array = []
    # 遍历结果
    for doc in result:
        info = {
            "name": doc["姓名"],
            "gender": doc["性别"],
            "university": doc["毕业院校"],
            "work_years": doc["工作经验年限"],
            "file_name": doc["文件名"]
        }

        json_array.append(info)
        
    client.close()  # 关闭连接
    return jsonify(json_array)


@blue.route('/log', methods=['POST'])
def log():
    data = request.get_json()      
    print(data)
    user_name = data["username"]
    client = MongoClient(Config.MONGO_URL)
    # 选择数据库
    db = client[Config.MONGO_DB]
    # 选择集合（即表）
    collection = db[Config.MONGO_COL]
    json_array = []
# print(user_name)
    result = collection.find({"用户": user_name})
    for doc in result:
        info = {
            "date": doc["上传时间"],
            "file_name": doc["文件名"],
            "name": doc["姓名"],
        }
        json_array.append(info)
    print(json_array)
    client.close()
    return jsonify(json_array)
